package com.opencms.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.opencms.bean.Channel;
import com.opencms.bean.ChannelModel;
import com.opencms.dao.ChannelMapper;
import com.opencms.dao.ChannelModelMapper;
import com.opencms.dao.base.MapperSupport;
import com.opencms.service.ChannelService;
import com.opencms.service.base.impl.ServiceSupportImpl;

@Service
public class ChannelServiceImpl extends ServiceSupportImpl<Channel> implements
		ChannelService {
	@Autowired
	private ChannelMapper channelMapper;
	
	@Autowired
	private ChannelModelMapper channelModelMapper;

	@Override
	public MapperSupport<Channel> getMapperSupport() {
		return channelMapper;
	}

	@Override
	public Channel selectByCode(String code) {
		return channelMapper.selectByCode(code);
	}
	
	public void saveOrUpdate(Channel channel,String modelIds){
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("channelId",channel.getId());
		channelModelMapper.deleteByParams(params);
		if (StringUtils.isNotBlank(modelIds)) {
			String[] ids=StringUtils.split(modelIds,",");
			for (int i = 0; i < ids.length; i++) {
				ChannelModel channelModel = new ChannelModel();
				channelModel.setChannelId(channel.getId());
				channelModel.setModelId(Integer.valueOf(ids[i]));
				channelModelMapper.insertSelective(channelModel);
			}
		}
		if(channel.getId()!=null){
			channelMapper.updateByPrimaryKeySelective(channel);
		}else{
			channelMapper.insertSelective(channel);
		}
	}
}
